<template>
  <div class="picture-List">
    <!-- 图片列表 -->
    <a-list
      :grid="{ gutter: 16, xs: 1, sm: 2, md: 3, lg: 4, xl: 5, xxl: 6 }"
      :data-source="dataList"
      :loading="loading"
    >
      <template #renderItem="{ item: picture }">
        <a-list-item style="padding: 0">
          <!-- 单张图片 -->
          <a-card hoverable style="width: 238px" @click="doClickPictureCard(picture)">
            <template #cover>
              <img
                :alt="picture.name"
                :src="picture.thumbnailUrl ?? picture.url"
                style="height: 180px; object-fit: cover"
              />
            </template>
            <a-card-meta :title="picture.name" type="inner">
              <template #description>
                <div style="margin-bottom: 3px">
                  分类：
                  <a-tag color="green">
                    {{ picture.category }}
                  </a-tag>
                </div>
                <div>
                  标签：
                  <a-tag v-for="tag in picture.tags" style="margin-bottom: 3px">
                    {{ tag }}
                  </a-tag>
                </div>
              </template>
            </a-card-meta>
            <template v-if="spaceId" #actions>
              <!-- 图片快捷操作 -->
              <!-- 下载原图 -->
              <a-button
                size="large"
                type="text"
                title="下载原图"
                :style="{ color: '#5897FB' }"
                @click="(down) => downloadOrigin(picture, down)"
                v-if="picture.originView === 1"
              >
                <template #icon>
                  <DownloadOutlined />
                </template>
              </a-button>
              <!-- 下载压缩 -->
              <a-button
                size="large"
                type="text"
                title="下载高清压缩图"
                :style="{ color: '#5897FB' }"
                @click="(down) => downloadCompressed(picture, down)"
                v-if="picture.originView === 0"
              >
                <template #icon>
                  <DownloadOutlined />
                </template>
              </a-button>
              <!-- 下载缩略图 -->
              <a-button
                size="large"
                type="text"
                title="原图、高清压缩图丢失，点击下载缩略图"
                :style="{ color: '#5897FB' }"
                @click="(down) => downloadThumbnail(picture, down)"
                v-if="picture.originView !== 1 && picture.originView !== 0"
              >
                <template #icon>
                  <CompressOutlined />
                </template>
              </a-button>
              <!-- 分享图片 -->
              <a-button
                size="large"
                :icon="h(ShareAltOutlined)"
                type="text"
                title="分享这张图片给小伙伴们"
                :style="{ color: '#5897FB' }"
                @click="(share) => doShare(picture, share)"
              >
              </a-button>
              <!-- 编辑图片 -->
              <a-button
                v-if="canEdit"
                size="large"
                :icon="h(EditOutlined)"
                type="text"
                title="编辑图片信息"
                @click="(edit) => doEdit(picture, edit)"
              />
              <!-- 删除图片 -->
              <a-popconfirm
                title="确定删除该图片吗？"
                ok-text="确认"
                cancel-text="取消"
                @confirm="() => doDelete(picture)"
                @cancel="cancelDelete"
              >
                <a-button
                  v-if="canDelete"
                  size="large"
                  :icon="h(DeleteOutlined)"
                  danger
                  style="opacity: 85%"
                  type="text"
                  title="从云中删除图片"
                  @click="
                    (e) => {
                      e.stopPropagation()
                      e.preventDefault()
                    }
                  "
                />
              </a-popconfirm>
            </template>
          </a-card>
        </a-list-item>
      </template>
    </a-list>
    <ShareModal ref="shareModalRef" :link="shareLink" />
  </div>
</template>

<script lang="ts" setup>
import { useRouter } from 'vue-router'
import { useLoginUserStore } from '@/stores/useLoginUserStores.ts'
import { h, ref } from 'vue'
import {
  CompressOutlined,
  DeleteOutlined,
  DownloadOutlined,
  EditOutlined,
  ShareAltOutlined,
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { deletePictureUsingPost } from '@/api/pictureController.ts'
import { downloadImage } from '@/utils'
import ShareModal from '@/components/ShareModal.vue'

interface Props {
  dataList?: API.PictureVO[]
  spaceId?: number
  loading?: boolean
  onReload?: () => void
  canEdit?: boolean
  canDelete?: boolean
  publicFlag?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  dataList: () => [],
  // @ts-ignore
  spaceId: null,
  loading: false,
  canEdit: false,
  canDelete: false,
})

const router = useRouter()

// 点击图片卡片跳转图片详情页并在新标签页打开
const doClickPictureCard = (picture: API.PictureVO) => {
  const loginUserStore = useLoginUserStore()
  loginUserStore.fetchLoginUser()
  const loginUser = loginUserStore.loginUser
  if(props.publicFlag) {
    const url = `/picture/${picture.id}`
    if (loginUser.userName === '未登录') {
      // message.error('登录后查看图片信息')
      router.push(url)
    } else {
      window.open(url, '_blank')
    }
  } else {
    const url = `/pictureNoPublic/${picture.id}`
    if (loginUser.userName === '未登录') {
      // message.error('登录后查看图片信息')
      router.push(url)
    } else {
      window.open(url, '_blank')
    }
  }
}

// 下载原图
const downloadOrigin = (picture: API.PictureVO, down: Event) => {
  // 阻止冒泡
  down.stopPropagation()
  downloadImage(picture.originUrl)
}

// 下载压缩图
const downloadCompressed = (picture: API.PictureVO, down: Event) => {
  // 阻止冒泡
  down.stopPropagation()
  downloadImage(picture.url)
}

// 下载缩略图
const downloadThumbnail = (picture: API.PictureVO, down: Event) => {
  // 阻止冒泡
  down.stopPropagation()
  downloadImage(picture.thumbnailUrl)
}

// 分享弹窗引用
const shareModalRef = ref()
// 分享链接
const shareLink = ref<string>()
// 分享
const doShare = (picture: API.PictureVO, e: Event) => {
  e.stopPropagation()
  shareLink.value = `${window.location.protocol}//${window.location.host}/picture/${picture.id}`
  if (shareModalRef.value) {
    shareModalRef.value.openModal()
  }
}

// 编辑图片
const doEdit = (picture: API.PictureVO, edit: Event) => {
  // 阻止冒泡
  edit.stopPropagation()
  // 跳转时要携带所属空间Id，否则编辑图片后找不到所属空间
  router.push({
    path: '/edit_picture',
    query: {
      id: picture.id,
      spaceId: picture.spaceId,
    },
  })
}

/**
 * 删除图片
 * @param picture
 */
const doDelete = async (picture: API.PictureVO) => {
  // 在点击删除按钮时已经阻止冒泡
  // 这里是确认删除。不需要再阻止冒泡了
  // 前端校验一下id是否有效
  const id = picture.id
  if (!id) {
    message.error('删除失败，该图片已不存在')
    return
  }
  // @ts-ignore
  const res = await deletePictureUsingPost({ id })
  if (res.data.code === 0) {
    // 通知父组件刷新数据
    props.onReload?.()
    message.success('删除图片成功')
  } else {
    message.error('删除图片失败，' + res.data.message)
  }
}

/**
 * 取消删除图片
 * @param e
 */
const cancelDelete = (e: MouseEvent) => {
  message.success('取消删除')
}
</script>

<style scoped></style>
